//
//  SAAddStaffManagementVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/7/5.
//

#import "SAAddStaffManagementVC.h"
#import "SAAddModifyStaffCell.h"
#import "SAAddModifyFooter.h"
#import "SASystemEmpSaveAPI.h"
#import "NSString+MD5.h"
#import "SAModifyStaffPasswordView.h"
#import "SAStaffManagementModel.h"
#import "SASystemEmpUpdateAPI.h"
#import "SASystemEmpDetailAPI.h"
#import "BubbleTableView.h"
#import "SALoginVC.h"
#import "SASystemStoreStoreListAPI.h"
#import "SAStoreModel.h"
#import "BubbleTableView.h"

@interface SAAddStaffManagementVC ()<UITableViewDelegate, UITableViewDataSource, HTTPAPIDelegate>

@property (nonatomic, assign) SAAddModifyType type;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SAAddModifyFooter *tableFooter;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *placeholderArr;
@property (nonatomic, strong) NSMutableArray *contentMarr;
@property (nonatomic, strong) UIButton *completeBtn;
@property (nonatomic, strong) SASystemEmpSaveAPI *systemEmpSaveAPI;
@property (nonatomic, strong) NSString *password;
@property (nonatomic, strong) SAStaffManagementModel *model;
@property (nonatomic, strong) SASystemEmpUpdateAPI *systemEmpUpdateAPI;
@property (nonatomic, strong) SASystemEmpUpdateAPI *passWordUpdateAPI;
@property (nonatomic, strong) BubbleTableView *positionBubbleView;
@property (nonatomic, strong) UIImageView *allowImageV;
@property (nonatomic, assign) NSInteger positionType;

@property (nonatomic, strong) SASystemStoreStoreListAPI *systemStoreStoreListAPI;
@property (nonatomic, strong) NSMutableArray<SAStoreModel *> *storeList;
@property (nonatomic, strong) BubbleTableView *storeBubbleView;
@property (nonatomic, assign) NSInteger storeRow;
@property (nonatomic, strong) UIImageView *allowImageV2;

@end

@implementation SAAddStaffManagementVC

- (instancetype)initWithType:(SAAddModifyType)type AndManagementModel:(SAStaffManagementModel *)model {
    if (self = [super init]) {
        self.type = type;
        self.model = model;
        if (model.userName.length == 0) {
            model.userName = @"";
        }
        if (model.empName.length == 0) {
            model.empName = @"";
        }
        if (model.mobile.length == 0) {
            model.mobile = @"";
        }
        if (model.enable.length == 0) {
            model.enable = @"";
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)initData {
    WeakSelf
    self.tableFooter.changePasswordBlock = ^{
        SAModifyStaffPasswordView *passwordView = [SAModifyStaffPasswordView shareCornView];
        passwordView.finishBlock = ^(NSString * _Nonnull password) {
            weakSelf.passWordUpdateAPI.password = password;
            [weakSelf.passWordUpdateAPI sendRequestToServerWithActivityViewAndMask:POST];
        };
        [passwordView showView:weakSelf];
    };
    
    if (self.type == SAAddModifyType_Add) {
        self.positionType = -1;
    }else {
        
        self.systemEmpUpdateAPI.empId = self.model.empId;
        self.systemEmpUpdateAPI.empType = self.model.empType;
        self.systemEmpUpdateAPI.enable = self.model.enable;
        self.systemEmpUpdateAPI.empName = self.model.empName;
        self.systemEmpUpdateAPI.mobile = self.model.mobile;
        if ([self.model.empType isEqualToString:@"1"]) {
            self.systemEmpUpdateAPI.enable = @"1";
            self.systemEmpUpdateAPI.empType = @"1";
            self.positionType = -1;
        }else {
            self.positionType = [self.model.empType intValue] - 2;
        }
        
        //修改密码专用
        self.passWordUpdateAPI.empId = self.model.empId;
        self.passWordUpdateAPI.empType = self.model.empType;
        self.passWordUpdateAPI.enable = self.model.enable;
        self.passWordUpdateAPI.empName = self.model.empName;
        self.passWordUpdateAPI.mobile = self.model.mobile;
        if ([self.model.empType isEqualToString:@"1"]) {
            self.passWordUpdateAPI.enable = @"1";
            self.passWordUpdateAPI.empType = @"1";
        }
    }
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemEmpSaveAPI == api) {
        [Prompt popPromptViewWithMsg:@"新增员工成功" duration:2];
        !self.reloadBlock ?: self.reloadBlock();
        [self.navigationController popViewControllerAnimated:YES];
    }else if (self.systemEmpUpdateAPI == api) {
        if ([self.model.empType isEqualToString:@"1"]) {
            [Prompt popPromptViewWithMsg:@"修改老板成功" duration:2];
        }else {
            [Prompt popPromptViewWithMsg:@"修改员工成功" duration:2];
        }
        !self.reloadBlock ?: self.reloadBlock();
        [self.navigationController popViewControllerAnimated:YES];
    }else if (self.passWordUpdateAPI == api) {
        [Prompt popPromptViewWithMsg:@"修改密码成功" duration:2];
        !self.reloadBlock ?: self.reloadBlock();
    }else if (self.systemStoreStoreListAPI == api) {
        self.storeList = [SAStoreModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        [self showStoreList];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

#pragma mark - UITableView Delegate & DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAAddModifyStaffCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAAddModifyStaffCell"];
//    if ([self.model.empType isEqualToString:@"1"]) {
//        cell.isBoss = YES;
//    }else {
//        cell.isBoss = NO;
//    }
    [cell refreshCellWithTitle:self.titleArr[indexPath.row] placeHolder:self.placeholderArr[indexPath.row] content:self.contentMarr[indexPath.row]];
    if (self.type == SAAddModifyType_Modify) {
        if ([self.titleArr[indexPath.row] isEqualToString:@"店铺*"]) {
            cell.typeBtn.hidden = YES;
            cell.imageV.hidden = YES;
        }
    }
    WeakSelf
    cell.positionBlock = ^{
        if ([weakSelf.titleArr[indexPath.row] isEqualToString:@"岗位*"]) {
            [weakSelf positionSelect];
        }else {
            [weakSelf clickedAllowBtn2];
        }
    };
    cell.textFieldBlock = ^(NSString *title, NSString *content) {
        if ([title isEqualToString:@"手机*"]) {
            weakSelf.contentMarr[0] = content;
        }else if ([title isEqualToString:@"姓名*"]) {
            weakSelf.contentMarr[1] = content;
        }else if ([title isEqualToString:@"密码*"]) {
            weakSelf.contentMarr[2] = content;
        }
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(46);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

#pragma mark - event
-(void)confirmationTapEvent {
    [self.view endEditing:YES];
    
    if (self.type == SAAddModifyType_Add) {
        NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
        NSString *saveEmp = [NSString stringWithFormat:@"%@",menuList[9][@"perms"][@"saveEmp"]];
        if ([saveEmp isEqualToString:@"1"]) {
            [Prompt popPromptViewWithMsg:@"您没有新增员工权限,请联系店长添加" duration:2];
            return;
        }
        
        self.systemEmpSaveAPI.mobile = self.contentMarr[0];
        self.systemEmpSaveAPI.empName = self.contentMarr[1];
        self.password = self.contentMarr[2];
        
        if (self.systemEmpSaveAPI.mobile.length == 0) {
            [Prompt popPromptViewWithMsg:@"手机号不能为空！" duration:2];
            return;
        }
        if (self.systemEmpSaveAPI.empName.length == 0) {
            [Prompt popPromptViewWithMsg:@"姓名不能为空！" duration:2];
            return;
        }
        if (self.password.length == 0) {
            [Prompt popPromptViewWithMsg:@"密码不能为空！" duration:2];
            return;
        }
        if ((self.password.length < 6) ||(self.password.length > 20)) {
            [Prompt popPromptViewWithMsg:@"请输入6-20位的密码！" duration:2];
            return;
        }
        if (self.storeRow < 0) {
            [Prompt popPromptViewWithMsg:@"店铺不能为空！" duration:2];
            return;
        }
        if (self.positionType == -1) {
            [Prompt popPromptViewWithMsg:@"岗位不能为空！" duration:2];
            return;
        }
        self.systemEmpSaveAPI.merchantId = @(self.storeList[self.storeRow].merchantId).stringValue;
        self.systemEmpSaveAPI.password = [NSString stringToMD5:self.password];
        self.systemEmpSaveAPI.empType = @"3";
        self.systemEmpSaveAPI.enable = @"1";
        self.systemEmpSaveAPI.empType = [NSString stringWithFormat:@"%zd",self.positionType + 2];
        [self.systemEmpSaveAPI sendRequestToServerWithActivityViewAndMask:POST];
    }else {
        NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
        NSString *modifyEmp = [NSString stringWithFormat:@"%@",menuList[9][@"perms"][@"modifyEmp"]];
        if ([modifyEmp isEqualToString:@"1"]) {
            [Prompt popPromptViewWithMsg:@"您没有修改员工权限,请联系店长添加" duration:2];
            return;
        }
        
        if (self.systemEmpUpdateAPI.mobile.length == 0) {
            [Prompt popPromptViewWithMsg:@"手机号不能为空！" duration:2];
            return;
        }
        if (self.systemEmpUpdateAPI.empName.length == 0) {
            [Prompt popPromptViewWithMsg:@"姓名不能为空！" duration:2];
            return;
        }
        self.systemEmpUpdateAPI.mobile = self.contentMarr[0];
        self.systemEmpUpdateAPI.empName = self.contentMarr[1];
        if ([self.model.empType isEqualToString:@"1"]) {
            self.systemEmpUpdateAPI.empType = @"1";
            self.systemEmpUpdateAPI.enable = @"1";
        }else {
            self.systemEmpUpdateAPI.empType = [NSString stringWithFormat:@"%zd",self.positionType + 2];
        }
        [self.systemEmpUpdateAPI sendRequestToServerWithActivityViewAndMask:POST];
    }
}

-(void)clickedAllowBtn2 {
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *crossStoreEmp = [NSString stringWithFormat:@"%@",menuList[9][@"perms"][@"crossStoreEmp"]];
    if ([crossStoreEmp isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有跨店查员工权限,请联系店长添加" duration:2];
        return;
    }
    
    if (self.storeList.count > 0) {
        [self showStoreList];
    }else {
        self.systemStoreStoreListAPI.returnAll = @"false";
        [self.systemStoreStoreListAPI sendRequestToServerWithActivityViewAndMask:GET];
    }
}
    
-(void)showStoreList{
    NSMutableArray *marr = [NSMutableArray array];
    for (SAStoreModel *model in self.storeList) {
        if (model.storeName.length == 0) {
            model.storeName = @"";
        }
        [marr addObject:model.storeName];
    }
    NSInteger height = marr.count * 50 + 10;
    if (height > 190) {
        height = 190;
    }
    NSArray *arr = nil;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    if (!self.storeBubbleView) {
        self.storeBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentRight) width:120 height:height cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.storeRow = row;
            if (self.type == SAAddModifyType_Add) {
                self.contentMarr[3] = rowString;
            }else {
                self.contentMarr[2] = rowString;
            }
            [self.tableView reloadData];
        } hideBlock:^{
            self.storeBubbleView = nil;
        }];
        [self.storeBubbleView showWithTargetView:self.allowImageV maskSuperView:window];
        [self.storeBubbleView updateBubble:marr fromDataArray:arr];// 更新气泡弹框
        self.storeBubbleView.bubbleCellHeight = 50;
        self.storeBubbleView.selectRow = self.storeRow;
        self.storeBubbleView.isBubbleScrollEnabled = YES;
        self.storeBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }
}

-(void)positionSelect {
    if([self.model.empType isEqualToString:@"1"]) {
        return;
    }
    
    NSMutableArray *marr = [NSMutableArray arrayWithObjects:@"店长", @"营业员", @"收银员", nil];
    NSInteger height = marr.count * 50 + 10;
    if (height > 190) {
        height = 190;
    }
    NSArray *arr = nil;
    UIView *window = [UIApplication sharedApplication].keyWindow;
    if (!self.positionBubbleView) {
        self.positionBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentRight) width:120 height:height cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.positionType = row;
            if (self.type == SAAddModifyType_Add) {
                self.contentMarr[4] = rowString;
            }else {
                self.contentMarr[3] = rowString;
            }
            [self.tableView reloadData];
        } hideBlock:^{
            self.positionBubbleView = nil;
        }];
        [self.positionBubbleView showWithTargetView:self.allowImageV2 maskSuperView:window];
        [self.positionBubbleView updateBubble:marr fromDataArray:arr];// 更新气泡弹框
        self.positionBubbleView.bubbleCellHeight = 50;
        self.positionBubbleView.selectRow = self.positionType;
        self.positionBubbleView.isBubbleScrollEnabled = YES;
        self.positionBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }
}

//-(void)ExitLogin {
//    // 延迟2秒执行：
//    double delayInSeconds = 2;
//    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//        [SAValueManger shareInStance].userInfo = nil;
//        [kUserDefault setObject:@"" forKey:kAotuLoginKey];
//        UIWindow *window =  [UIApplication sharedApplication].keyWindow;
//        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[SALoginVC new]];
//        window.rootViewController = nav;
//        [window makeKeyAndVisible];
//    });
//}

#pragma mark - initUI
- (void)initUI {
    self.storeRow = -1;
    if (self.type == SAAddModifyType_Add) {
        [self setNavigationItemBackBBIAndTitle:@"新增员工"];
    } else {
        if ([self.model.empType isEqualToString:@"1"]) {
            [self setNavigationItemBackBBIAndTitle:@"修改老板"];
        }else {
            [self setNavigationItemBackBBIAndTitle:@"修改员工"];
        }
    }
    
    [self addRightViews:@[self.completeBtn]];
    [self setBgImage:nil];
    [self.view addSubview:self.allowImageV];
    [self.view addSubview:self.allowImageV2];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(kScaleNum(StatusHeight), 0, 0, 0));
    }];
}

#pragma mark - lazy init

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kColor(240, 240, 240, 1);
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.bounces = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        WeakSelf
        if (self.type == SAAddModifyType_Modify) {
            _tableView.tableFooterView = weakSelf.tableFooter;
        }
        [_tableView registerClass:[SAAddModifyStaffCell class] forCellReuseIdentifier:@"SAAddModifyStaffCell"];
        
    }
    return _tableView;
}

- (SAAddModifyFooter *)tableFooter {
    if (!_tableFooter) {
        _tableFooter = [[SAAddModifyFooter alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(80))];
    }
    return _tableFooter;
}

- (NSArray *)titleArr {
    if (!_titleArr) {
        if (self.type == SAAddModifyType_Add) {
            _titleArr = @[@"手机*", @"姓名*", @"密码*", @"店铺*", @"岗位*"];
        } else {
            _titleArr = @[@"手机*", @"姓名*",@"店铺*", @"岗位*"];
        }
    }
    return _titleArr;
}

- (NSArray *)placeholderArr {
    if (!_placeholderArr) {
        if (self.type == SAAddModifyType_Add) {
            _placeholderArr = @[@"请输入手机号", @"请输入姓名", @"请输入密码", @"请选择店铺",@"请选择岗位"];
        } else {
            _placeholderArr = @[@"请输入手机号", @"请输入姓名", @"", @""];
        }
    }
    return _placeholderArr;
}

- (NSMutableArray *)contentMarr {
    if (!_contentMarr) {
        if (self.type == SAAddModifyType_Add) {
            _contentMarr = [NSMutableArray arrayWithObjects:@"", @"", @"", @"", @"", nil];
        } else {
            NSString *type = @"老板";
            if ([self.model.empType isEqualToString:@"2"]) {
                type = @"店长";
            }else if ([self.model.empType isEqualToString:@"3"]) {
                type = @"营业员";
            } else if ([self.model.empType isEqualToString:@"4"]) {
                type = @"收银员";
            }
            _contentMarr = [NSMutableArray arrayWithObjects:self.model.mobile, self.model.empName, self.model.storeName, type, nil];
        }
    }
    return _contentMarr;
}

-(UIButton *)completeBtn {
    if (!_completeBtn) {
        _completeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_completeBtn setTitle:@"完成" forState:UIControlStateNormal];
        _completeBtn.frame = SARectMake(254, 0, 85, 44);
        _completeBtn.titleLabel.font = kFont(16);
        [_completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_completeBtn addTarget:self action:@selector(confirmationTapEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    return _completeBtn;
}

-(SASystemEmpSaveAPI *)systemEmpSaveAPI {
    if (!_systemEmpSaveAPI) {
        _systemEmpSaveAPI = [SASystemEmpSaveAPI apiWithDelegate:self];
    }
    return _systemEmpSaveAPI;
}

-(SASystemEmpUpdateAPI *)systemEmpUpdateAPI {
    if (!_systemEmpUpdateAPI) {
        _systemEmpUpdateAPI = [SASystemEmpUpdateAPI apiWithDelegate:self];
    }
    return _systemEmpUpdateAPI;
}

-(SASystemEmpUpdateAPI *)passWordUpdateAPI {
    if (!_passWordUpdateAPI) {
        _passWordUpdateAPI = [SASystemEmpUpdateAPI apiWithDelegate:self];
    }
    return _passWordUpdateAPI;
}

-(UIImageView *)allowImageV {
    if (!_allowImageV) {
        _allowImageV = [[UIImageView alloc] initWithFrame:SARectMake(kBaseScreenWidth - 48, StatusHeight + 145, 38, 40)];
        _allowImageV.userInteractionEnabled = NO;
        if (self.type == SAAddModifyType_Modify) {
            _allowImageV.frame = SARectMake(kBaseScreenWidth - 48, StatusHeight + 97, 38, 40);
        }
    }
    return _allowImageV;
}

-(UIImageView *)allowImageV2 {
    if (!_allowImageV2) {
        _allowImageV2 = [[UIImageView alloc] initWithFrame:SARectMake(kBaseScreenWidth - 48, StatusHeight + 191, 38, 40)];
        _allowImageV2.userInteractionEnabled = NO;
        if (self.type == SAAddModifyType_Modify) {
            _allowImageV2.frame = SARectMake(kBaseScreenWidth - 48, StatusHeight + 143, 38, 40);
        }
    }
    return _allowImageV2;
}

-(SASystemStoreStoreListAPI *)systemStoreStoreListAPI {
    if (!_systemStoreStoreListAPI) {
        _systemStoreStoreListAPI = [SASystemStoreStoreListAPI apiWithDelegate:self];
    }
    return _systemStoreStoreListAPI;
}

-(NSMutableArray<SAStoreModel *> *)storeList {
    if (!_storeList) {
        _storeList = [NSMutableArray array];
    }
    return _storeList;
}

@end

